package com.shop.controller;

import com.alibaba.fastjson.JSONObject;
import com.shop.commom.utils.CookieUtils;
import com.shop.commom.utils.JSONResult;
import com.shop.pojo.Users;
import com.shop.service.UsersService;
import com.shop.vo.UsersSaveRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.security.NoSuchAlgorithmException;

@RestController
@RequestMapping("passport")
public class PassPortController {

    @Autowired
    private UsersService usersService;


    @GetMapping("/usernameIsExist")
    public JSONResult usernameIsExist(@RequestParam String username){
        if(StringUtils.isBlank(username)){
            return JSONResult.error("用户名不能为空!");
        }
        boolean b = usersService.queryUserNameIsExist(username);
        if(b){
            return JSONResult.error("用户名已存在!");
        }else{
            return JSONResult.OK();
        }
    }

    @PostMapping("/regist")
    public JSONResult createUsers(@RequestBody @Valid UsersSaveRequest request) throws NoSuchAlgorithmException {
        return JSONResult.OK(usersService.createUser(request));
    }


    @PostMapping("/login")
    public JSONResult login(@RequestBody @Valid UsersSaveRequest request, HttpServletRequest servletRequest, HttpServletResponse response) throws NoSuchAlgorithmException {
        Users users = usersService.queryUserForLogin(request.getUsername(), request.getPassword());
        CookieUtils.setCookie(servletRequest,response,"user", JSONObject.toJSONString(users),true);
        return JSONResult.OK(users);
    }

    @PostMapping("/logout")
    public JSONResult logout(HttpServletRequest servletRequest, HttpServletResponse response) throws NoSuchAlgorithmException {
        CookieUtils.deleteCookie(servletRequest,response,"user");
        return JSONResult.OK();
    }


}
